﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Practices.Unity;

namespace ERPStore.Web.Start
{
	public class SiteConfig
	{
		public static void Configure(Microsoft.Practices.Unity.IUnityContainer container, System.Web.HttpContextBase ctx)
		{
			// Resolution et chargement des paramètres de configuration du site
			var settingsService = container.Resolve<ERPStore.Services.ISettingsService>();
			var settings = settingsService.GetWebSiteSettings();
			if (settings == null) // First run
			{
				throw new Exception("Settings does not exists");
			}

			var tempPath = ERPStore.Configuration.ConfigurationSettings.AppSettings["tempPath"] ?? System.IO.Path.GetTempPath();
			if (tempPath.StartsWith(@".\"))
			{
				tempPath = ctx.Server.MapPath(tempPath);
			}
			settings.TempPath = tempPath;
			var imagePath = ERPStore.Configuration.ConfigurationSettings.AppSettings["imagePath"] ?? tempPath;
			if (imagePath.StartsWith(@".\"))
			{
				tempPath = ctx.Server.MapPath(imagePath);
			}
			settings.ImagePath = imagePath;
			settings.CurrentUrl = string.Format("http://{0}", ctx.Request.Url.Host);
			settings.PhysicalPath = ctx.Server.MapPath("/");

			GlobalConfiguration.Configuration.Settings = settings;

			// Configuration du cryptage
			var injectionMembers = new InjectionMember[] 
			{ 
				new InjectionConstructor(GlobalConfiguration.Configuration.Settings.CryptoKey, GlobalConfiguration.Configuration.Settings.CryptoIV) ,
			};
			container.RegisterType<ERPStore.Services.CryptoService>(new ContainerControlledLifetimeManager(), injectionMembers);

			GlobalConfiguration.Configuration.Logger.Info("Website configuration enabled");
		}

	}
}
